package com.netty.channel;

import java.util.ArrayList;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock.ReadLock;
import java.util.concurrent.locks.ReentrantReadWriteLock.WriteLock;

import io.netty.channel.Channel;

/**
 * channel集合，线程安全
 * 
 * @author zhoufang
 *
 *         2017年12月23日下午11:26:08
 */
public class ChannelVector {

	/** 当前保存的channels */
	private ArrayList<Channel> channels = new ArrayList<Channel>();
	/** 当前消息索引 */
	private AtomicInteger msgIndex = new AtomicInteger(0);
	/** 读写锁 */
	private ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
	private ReadLock readLock = lock.readLock();
	private WriteLock writeLock = lock.writeLock();

	/**
	 * 随机获取一个channel
	 * 
	 * @return
	 */
	public Channel randomChannel() {
		this.readLock.lock();
		try {
			if (channels.isEmpty()) {
				return null;
			}
			int next = msgIndex.incrementAndGet();
			int index = next % channels.size();
			return channels.get(index);
		} finally {
			this.readLock.unlock();
		}
	}

	/**
	 * 增加1个channel
	 * 
	 * @param channel
	 */
	public void addChannel(Channel channel) {
		this.writeLock.lock();
		try {
			this.channels.add(channel);
		} finally {
			this.writeLock.unlock();
		}
	}

	/**
	 * 移除1个channel
	 * 
	 * @param channel
	 */
	public void removeChannel(Channel channel) {
		this.writeLock.lock();
		try {
			this.channels.remove(channel);
		} finally {
			this.writeLock.unlock();
		}
	}

}
